<template>
  <div class="page">
    <!-- 导航栏 -->
    <uni-nav-bar fixed="true" title="编辑标题和描述" statusBar="true" :border="false" left-icon="left"
      @clickLeft="back"></uni-nav-bar>
    <!-- 页面主体 -->
    <div class="container">
      <div class="edit-box">
        <text class="title">问卷标题</text>
        <div class="tip" v-if="isShowTitleTip">例如：小蔡和小美的婚礼</div>
        <textarea class="title-textarea" type="text" placeholder="请输入标题" :maxlength="20" placeholder-class="placeholder"
          :focus="isFocusTitle" auto-height v-model="questionnaireInfo.title" @blur="titleBlurHandle"
          @focus="titleFocusHandle" />
      </div>
      <div class="edit-box">
        <text class="title">婚礼时间</text>
        <div class="date" :class="isSetDeadline ? '' : 'date-tip'" @click="dateClickHandle">{{
          isSetDeadline ?
          questionnaireInfo.deadline : '请输入婚礼时间' }}
        </div>
      </div>
      <div class="edit-box describe">
        <text class="title">问卷描述</text>
        <div class="textarea" type="text" placeholder="请输入描述" auto-height placeholder-class="placeholder">
          {{ questionnaireInfo.desc }}
        </div>
        <button class="custom-btn" @click="customClickHandle('describe')">自定义</button>
      </div>
      <div class="edit-box">
        <text class="title">问卷结束语</text>
        <div class="textarea" type="text" placeholder="请输入描述" placeholder-class="placeholder">{{
          questionnaireInfo.conclusion }}</div>
        <button class="custom-btn" @click="customClickHandle('conclusion')">自定义</button>
      </div>
      <div class="bottom-bar">
        <button class="confirm-btn" @click="confirmHandle">确定</button>
      </div>
    </div>
  </div>

  <!-- 输入「描述」或「结束语」的编辑弹窗 -->
  <uni-popup ref="customPopup" :is-mask-click="false" mask-background-color="rgba(0,0,0,.6)">
    <div class="popup-container">
      <!-- 中间的弹窗 -->
      <div class="popup">
        <div class="title">自定义文案</div>
        <textarea class="input" type="text" :maxlength="120" placeholder="请输入内容" placeholder-style="color: #9f9f9f;"
          v-model="inputContent" />
        <!-- 输入框字数 -->
        <div class="input-count">{{ Math.min(inputContent.length, 120) }}/120</div>
        <div class="btn confirm-btn" @click="customConfirmHandle">确定</div>
      </div>
      <!-- 关闭按钮 -->
      <img class="close-btn" src="@/static/icons/common/close-circle.svg" @click="customCloseHandle">
    </div>
  </uni-popup>
  <!-- 提示弹窗 -->
  <uni-popup ref="tipPopup" type="dialog">
    <uni-popup-dialog mode="base" title="提示" type="info" content="已经创建好的问卷仅可以重新设置问卷标题、婚礼时间、问卷描述、问卷结束语" cancelText="取消"
      confirmText="知道了" @close="tipCancelHandle" @confirm="tipConfirmHandle"></uni-popup-dialog>
  </uni-popup>
  <!-- 日期选择器 -->
  <myDateTime ref="datePicker" :time-str="dayjs().format('YYYY-MM-DD')" :start-date="dayjs().format('YYYY-MM-DD')"
    @change="dateChangeHandle" :title-show="false" :show-num="3">
  </myDateTime>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { back, navigateTo } from '@/utils/navigate';
import { useQuestionnaire } from '@/stores/questionnaire';
import { storeToRefs } from 'pinia';
import { onLoad } from '@dcloudio/uni-app';
import dayjs from 'dayjs'

import { showToast } from '@/utils/tools';
import { getCurrentInstance } from 'vue';
import { onMounted } from 'vue';
import myDateTime from '@/components/my-datetime.vue'

/** 当前页面（组件）实例 */
const currentInstance = getCurrentInstance()
// store
const questionnaire = useQuestionnaire()
const { currentQuestionnaire } = storeToRefs(questionnaire)
const { getAndSetCurrentQuestionnaire, editCurrentQuestionnaire } = questionnaire


/** 问卷信息 */
const questionnaireInfo = ref({
  /** 问卷标题 */
  title: '',
  /** 截止时间，默认为10天后 */
  deadline: new Date(Date.now() + 10 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10),
  /** 问卷描述 */
  desc: '',
  /** 结束语 */
  conclusion: '致新人：婚礼是一场仪式也是一份回忆，Ta应该和你们的感情一样 简单 纯粹 走心 不娇柔做作 不煽情，因为真情就足以打动人心',
})

/** 初始化问卷信息 */
const initQuestionnaireInfo = () => {
  questionnaireInfo.value = {
    /** 问卷标题 */
    title: currentQuestionnaire?.value?.title || '',
    /** 截止时间，默认为10天后 */
    deadline: currentQuestionnaire?.value?.deadline || new Date(Date.now() + 10 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10),
    /** 问卷描述 */
    desc: currentQuestionnaire?.value?.desc || '',
    /** 结束语 */
    conclusion: currentQuestionnaire?.value?.conclusion || '致新人：婚礼是一场仪式也是一份回忆，Ta应该和你们的感情一样 简单 纯粹 走心 不娇柔做作 不煽情，因为真情就足以打动人心',
  }
}

onLoad(() => {
  initQuestionnaireInfo()
})

//#region 标题相关

/** 是否聚焦到标题输入栏 */
const isFocusTitle = ref(false)

/**
 * 切换标题输入栏聚焦或失去焦点
 * @param isFocus 是否聚焦
 */
const toggleTitleFocus = (isFocus: boolean) => {
  isFocusTitle.value = isFocus
}

/** 标题输入栏失去焦点时的回调 */
const titleBlurHandle = () => {
  console.log('titleBlurHandle', isFocusTitle.value)
  isFocusTitle.value = false
}

/** 标题输入栏聚焦时的回调 */
const titleFocusHandle = () => {
  console.log('titleFocusHandle', isFocusTitle.value)
  isFocusTitle.value = true
}

// 是否显示标题输入提示语
const isShowTitleTip = ref(true)

//#endregion

//#region 设置婚礼时间相关

/** 是否设置了婚礼时间 */
const isSetDeadline = ref(false)

// 页面加载后判断是否显示婚礼时间
onLoad((options) => {
  // 如果是从问卷卡片点击进入的，则不显示标题提示语，且显示婚礼时间
  if (options!.from === 'questionnaire-card' || options!.from === 'create-questionnaire') {
    isShowTitleTip.value = false
    isSetDeadline.value = true
  }
})

/**
 * 切换婚礼时间选择器的显示状态
 * @param {boolean} isShow 是否显示
 */
const toggleDatePicker = (isShow: boolean) => {
  const datePicker: any = currentInstance?.refs?.datePicker
  if (!datePicker) return

  if (isShow) datePicker.open()
  else datePicker.close()
}

onMounted(() => {
  toggleDatePicker(false)
})

/** 点击婚礼时间输入框时的回调 */
const dateClickHandle = () => {
  toggleDatePicker(true)
}

/** 修改问卷时间回调 */
const dateChangeHandle = (e: any) => {
  questionnaireInfo.value.deadline = e
  console.log('e', e)
  console.log('dateChangeHandle', questionnaireInfo.value)
  isSetDeadline.value = true
}
//#endregion

//#region 「确定」按钮点击事件
/** 是否是从模板创建的问卷 */
let isFromTemplate = false

// 页面加载时判断是否是从模板创建的问卷
onLoad((options: any) => {
  isFromTemplate = options.from === 'template'
  if (isFromTemplate) {
    // 将标题清空
    questionnaireInfo.value.title = ''
  }
})

/** 是否是复制问卷 */
let isCopy = false

// 页面加载时判断是否是复制
onLoad(async (options: AnyObject | undefined) => {

  /** 原问卷的id */
  let originalQuestionnaireId = ''

  /** 原问卷的类型 */
  let originalQuestionnaireType: QuestionnaireCategory = 'created'

  if (options?.isCopy === 'true') {
    isCopy = true
    originalQuestionnaireId = options.originalQuestionnaireId
    originalQuestionnaireType = options.originalQuestionnaireType
    // 将目标问卷设置为当前编辑的问卷
    await getAndSetCurrentQuestionnaire(originalQuestionnaireId, originalQuestionnaireType)
    initQuestionnaireInfo()

    // 将标题清空
    questionnaireInfo.value.title = ''
  }

})


/** 「确定」按钮点击事件 */
const confirmHandle = async () => {
  if (!validateForm()) return

  // 更新当前编辑的问卷的信息
  questionnaire.editCurrentQuestionnaire(questionnaireInfo.value)
  console.log('currentQuestionnaire.value', currentQuestionnaire?.value)

  // 如果是复制问卷，则将id设置为空
  if (isCopy) {
    editCurrentQuestionnaire({ id: '', })
    console.log('currentQuestionnaire.value', currentQuestionnaire?.value)
  }

  let createRes: any = null
  try {
    // 保存编辑的问卷或复制问卷（id为空时）
    createRes = await questionnaire.saveCurrentQuestionnaire()
  } catch {
    showToast('保存失败 请稍后重试')
    return
  }

  // 如果是从模板创建的问卷，则跳转到「问卷查看」页面
  if (isFromTemplate) {
    const questionnaireId = createRes.data.data.question_id
    const questionnaireCategory = 'created'
    navigateTo('questionnaire-view', {
      questionnaireId,
      questionnaireCategory,
      from: 'create-questionnaire',
    })
    return
  }

  // 否则跳转到「婚礼问卷」页面
  navigateTo('survey')
  showToast('保存成功')
}

/**
 * 校验表单内容
 * @returns 是否校验通过
 */
const validateForm = () => {
  if (!questionnaireInfo.value.title) {
    showToast('请输入问卷标题')
    toggleTitleFocus(true)
    return false
  }
  if (!isSetDeadline.value) {
    showToast('请输入婚礼时间')
    const datePicker: any = currentInstance?.refs.datePicker
    datePicker.open()
    return false
  }
  if (!questionnaireInfo.value.desc) {
    showToast('请输入描述')
    return false
  }
  if (!questionnaireInfo.value.conclusion) {
    showToast('请输入结束语')
    return false
  }
  return true
}
// #endregion

//#region 编辑「描述」或「结束语」相关

/** 当前编辑的类型 */
const currentEditType = ref<'describe' | 'conclusion'>('describe')

/**
 * 「自定义」按钮点击事件
 * @param type 自定义的类型，'describe'为描述，'conclusion'为结束语
 */
const customClickHandle = (type: 'describe' | 'conclusion') => {
  currentEditType.value = type
  switch (type) {
    case 'describe':
      inputContent.value = questionnaireInfo.value.desc
      break
    case 'conclusion':
      inputContent.value = questionnaireInfo.value.conclusion
      break
  }
  toggleCustomPopup(true)
}

/**
 * 打开或关闭「自定义」弹窗
 * @param isOpen 是否打开
 */
const toggleCustomPopup = (isOpen: boolean) => {
  const popup: any = currentInstance?.refs.customPopup
  if (isOpen) {
    popup?.open()
  } else {
    popup?.close()
  }
}

/** 输入框内容 */
const inputContent = ref('test')

/** 「自定义」弹窗的「确定」按钮点击事件 */
const customConfirmHandle = () => {
  // 根据当前编辑的类型，修改对应的值
  switch (currentEditType.value) {
    case 'describe':
      questionnaireInfo.value.desc = inputContent.value
      break
    case 'conclusion':
      questionnaireInfo.value.conclusion = inputContent.value
      break
  }
  toggleCustomPopup(false)
}

/** 「自定义」弹窗的关闭按钮点击事件 */
const customCloseHandle = () => {
  toggleCustomPopup(false)
}
//#endregion

//#region 提示弹窗相关

/** 切换提示弹窗显示状态 */
const toggleTipPopup = (isOpen: boolean) => {
  console.log('instance', currentInstance)
  const popup: any = currentInstance?.refs.tipPopup
  if (isOpen) {
    popup?.open()
  } else {
    popup?.close()
  }
}

// 页面加载后判断是否显示
onLoad((options) => {
  // 如果是从问卷卡片点击进入的，则显示提示弹窗
  if (options!.from === 'questionnaire-card') {
    toggleTipPopup(true)
  }
  // 如果不是，则直接聚焦标题输入框
  else {
    setTimeout(() => {
      isFocusTitle.value = true
    }, 100);
  }
})

/** 「提示」弹窗的「取消」按钮点击事件 */
const tipCancelHandle = () => {
  toggleTipPopup(false)
  setTimeout(() => {
    isFocusTitle.value = true
  }, 100);
}

/** 「提示」弹窗的「知道了」按钮点击事件 */
const tipConfirmHandle = () => {
  toggleTipPopup(false)
  setTimeout(() => {
    isFocusTitle.value = true
  }, 100);
}
//#endregion
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background-color: #f2f8f3;

  .container {
    width: 100%;
    padding-top: 23.08rpx;

    .edit-box {
      width: 100%;
      min-height: 148.08rpx;
      background-color: #fff;

      box-sizing: border-box;
      padding: 20px 16px;
      margin-top: 1.92rpx;
      position: relative;

      .title {
        width: 115.38rpx;
        height: 40.38rpx;
        font-size: 28.85rpx;
        color: #666666;
        line-height: 40.38rpx;
      }

      // 提示文字
      .tip {
        margin-top: 5px;

        width: 100%;
        height: 40.38rpx;
        font-size: 28.85rpx;
        color: #666666;
        line-height: 40.38rpx;
      }


      // 日期的样式
      .date {
        margin-top: 5px;
        font-size: 32.69rpx;
        line-height: 32.69rpx;

        // 选择日期提示
        &.date-tip {
          margin-top: 5px;
          color: #999;
        }
      }




      .input {
        font-size: 32.69rpx;
        line-height: 32.69rpx;
      }

      // 标题输入框
      .title-textarea {
        width: calc(100% - 20vw);
        min-height: 25px;
        font-size: 32.69rpx;
        text-align: justify;

        // 输入框的占位符
        :deep(.placeholder) {
          color: #999;
        }
      }

      // 输入框
      .textarea {
        width: calc(100% - 20vw);
        font-size: 32.69rpx;
        line-height: 1.2;
        text-align: justify;

        // 输入框的占位符
        :deep(.placeholder) {
          color: #999;
        }
      }

      // 「自定义」按钮
      .custom-btn {
        position: absolute;
        right: 16px;
        top: 12vw;
        width: 14vw;
        height: 6.5vw;
        background: #17ce92;
        border-radius: 5px;

        display: flex;
        align-items: center;
        justify-content: center;

        font-size: 3.5vw;

        color: #ffffff;
      }
    }

    // 问卷描述
    .describe {
      margin-top: 12px;
    }

    .bottom-bar {
      position: fixed;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 25.1282vw;
      background-color: #fff;

      box-sizing: border-box;
      padding-bottom: 35px;
      display: flex;
      align-items: center;
      justify-content: center;

      .confirm-btn {
        width: 657.69rpx;
        height: 80.77rpx;
        background: #17ce92;
        border-radius: 7.69rpx;

        font-size: 30.77rpx;
        text-align: CENTER;
        color: #ffffff;
        line-height: 80.77rpx;
      }
    }
  }
}

// 「自定义」弹窗
.popup-container {
  width: 76.9231vw;

  display: grid;
  grid-template-rows: 1fr auto;
  grid-template-columns: 1fr;
  grid-row-gap: 39px;
  justify-items: center;

  // 弹窗主体
  .popup {
    width: 76.9231vw;
    height: 65vw;
    background: #ffffff;
    border-radius: 4px;

    padding: 16px;
    display: grid;
    grid-template:
      'title' 21px
      '.' 12px
      'input' 1fr
      '.' 12px
      'btn' 36px;
    justify-items: center;

    position: relative;

    // 标题
    .title {
      grid-area: title;

      font-size: 3.8462vw;
      color: #333;
    }

    // 输入框
    .input {
      grid-area: input;
      align-self: center;

      width: calc(76.9231vw - 32px);
      height: 30vw;
      border: 1px solid #17ce92;
      border-radius: 4px;

      box-sizing: border-box;
      padding: 5px 5px 20px 5px;

      // 文字两端对齐
      text-align: justify;
      font-size: 3.8462vw;

      // 占位文字样式
      &::moz-placeholder {
        color: red;
      }

    }

    // 输入框字数
    .input-count {
      position: absolute;
      right: 24px;
      bottom: 80px;

      font-size: 3.8462vw;
      color: #999;
    }

    // 「确定」按钮
    .btn {
      grid-area: btn;

      width: 68.7179vw;
      background: #17ce92;
      border-radius: 4px;

      // 文字居中
      display: flex;
      justify-content: center;
      align-items: center;

      font-size: 3.5897vw;
      color: #fff;
    }
  }

  // 取消按钮
  .close-btn {
    width: 8.7179vw;
    height: 8.7179vw;
  }
}
</style>
